<?php
namespace app\api\model;

use app\disk\controller\Dir;
use think\Model;
use think\Db;

/**
 * www.zhouchunyu.com.
 * Created on 2019/1/7 17:22
 * Created by One <admin@zhouchunyu.com>
 */

class Chunks extends Model {

    public $UID;
    public function __construct($uid = 0)
    {
        parent::__construct();
        $this->UID = $uid;
    }

    public function getChunksByMd5($md5='', $chunk_id=0) {
        $Obj = Db::name('chunks')->where('file_md5', $md5);
        if($chunk_id > 0) {
            $Obj->where('chunk_id', $chunk_id);
        }
        return $Obj->select();
    }

    public function SaveFile($data) {
        Db::name('chunks')->insert($data);
        return Db::name('chunks')->getLastInsID();
    }

    public function SaveChunk($file = null, $FileData = []) {
        $dir = ROOT_PATH . 'storage/chunks/' . $FileData['file_md5'] . '/';
        if(getDir($dir) == false) {
            error('文件夹创建失败');
        }
        $SavePath = $dir . $FileData['chunk_id'] . '.' . $FileData['file_md5'] . '.chunk';
        return file_put_contents($SavePath, $file) > 0 ? true : false;
    }

    public function AddChunk($data) {
        return $this->SaveFile($data);
    }

    public function chunk2file($data=[]) {
        $chunks = Db::name('chunks')->where('file_md5', $data['md5'])->order('chunk_id asc')->select();
        if(!$chunks) {
            $un_chunks = Db::name('chunks')->where('file_md5', $data['md5'])->delete();
            error('文件上传失败', 20002);
        }
        $dir = ROOT_PATH . 'storage/files/' . $data['md5'] . '/';
        $chunk_dir = ROOT_PATH . 'storage/chunks/' . $data['md5'] . '/';
        if(!getDir($dir)) {
            error('文件夹创建失败');
        }
        $loc_path = $data['md5'] . $data['file_name'];
        $SavePath = $dir . $loc_path;
        $deleteList=[];
        foreach ($chunks as $chunk) {
            $chunk_path =  $chunk_dir . $chunk['chunk_id'] . '.' . $chunk['file_md5'] . '.chunk';
            if(!file_exists($chunk_path)) {
                error('文件获取失败');
            }
            $content = file_get_contents($chunk_path);
            file_put_contents($SavePath, $content, FILE_APPEND);
            unset($content);
            @unlink($chunk_path);
            $deleteList[] = $chunk['id'];
        }
        rmdir($chunk_dir);

        $un_chunks = Db::name('chunks')->where('file_md5', $data['md5'])->delete();
        return [
            'file_name' => $data['file_name'],
            'loc_path' => $loc_path,
            'file_size' => $chunks[0]['file_size'],
            'file_md5' => $chunks[0]['file_md5']
        ];
    }

    public function merge($data=[]) {
        $file = $this->chunk2file($data);
        $FileData = [
            'uid' => $this->UID,
            'file_name' => $data['file_name'],
            'file_loc_path' => $file['loc_path'],
            'size' => $file['file_size'],
            'dir_id' => $data['save_path'],
            'file_md5' => $file['file_md5'],
            'update_time' => time(),
            'fileid' => create_guid(),
        ];

        Db::name('files')->insert($FileData);
        $File_id = Db::name('files')->getLastInsID();

        success(['file_id' => $File_id, 'file_path' => $data['save_path']]);
    }

}